from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import SecretStr

from settings import DASHSCOPE_API_KEY

# 1-定义客户端
llm = ChatOpenAI(
    model="qwen-max",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key=SecretStr(DASHSCOPE_API_KEY),
    streaming=True
)

# 2-定义消息-消息列表，显式指定每条消息的角色
messages = [
    ("system", "You are a helpful assistant."),
    ("user", "Tell me a joke about {topic}.")
]

# 2-先准备一个字符串模板(更推荐)
prompt_template = ChatPromptTemplate.from_messages(messages)

# 3-格式输入的消息内容-传入变量生成提示
chat_prompt_detail = prompt_template.invoke({"topic": "cats"})
print("----chat_prompt_detail:", chat_prompt_detail)

# 4-打印
print("-----Hold on, LLM 正在回答！-----")
response = llm.stream(chat_prompt_detail)
for chunk in response:
    # 打印不换行
    print(chunk.content, end="")
